import i18n from "@/i18n/i18n"
import axios from "axios"
import { Message, MessageBox } from "element-ui"
import { removeAuth } from "@/utils/auth"
import qs from "qs"
import { debounce } from "throttle-debounce"
import router from "../router"
import store from "@/store"
import { getKey } from "@/i18n/utils"

import { isBlob } from "@/utils/types"
//
// axios 0.18 支持不过滤掉自定义参数
// requestProp 额外的一些说明,与 data  method 同级
// disabledMessage 禁用消息弹框
//
/**
 * 检查dom是否忽略
 * @param {*} e
 */
const clearCacheEnterLogin = debounce(500, () => {
	// 已经在登录页面不清空
	const currentRoute = window.app.$route
	if (currentRoute && currentRoute.name === "login") {
		return
	}

	removeAuth({
		clearCookies: true
	})
		.then(() => {
			// location.reload() // 为了重新实例化vue-router对象 避免bug
		})
		.catch(() => {
			// location.reload()
		})
})

const errorMessage = debounce(500, (message, type = "error") => {
	Message({
		message: message,
		duration: 1500,
		type: type
	})
})

const confirmMessage = debounce(1000, message => {
	MessageBox.confirm(
		message,
		i18n.t("utils.847d683d7667ad5f481831f0ffd4473d"),
		{
			confirmButtonText: i18n.t("utils.4b59ddcd6ddfffb8bd5459a63a6e86ff"),
			showCancelButton: false,
			closeOnClickModal: false,
			closeOnPressEscape: false,
			showClose: false,
			type: "warning"
		}
	)
		.then(() => {
			if (
				(window.app.$route && window.app.$route.name !== "login") ||
				!window.app.$route
			) {
				clearCacheEnterLogin()
			} else {
				removeAuth({
					clearCookies: true
				})
			}
		})
		.catch(() => {})
})

axios.defaults.headers.post["Content-Type"] =
	"application/x-www-form-urlencoded;charset=UTF-8"
// 创建axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
	timeout: 600000 // 请求超时时间
})

const cancelTokenWhiteList = [
	"admin",
	"financeauth",
	"queryallemployeelist",
	"querytreelist",
	"login",
	"receivingemail"
]

// request拦截器
service.interceptors.request.use(
	config => {
		const flag =
			config.headers["Content-Type"] &&
			config.headers["Content-Type"].indexOf("application/json") !== -1
		if (!flag) {
			const mult =
				config.headers["Content-Type"] &&
				config.headers["Content-Type"].indexOf("multipart/form-data") !== -1
			if (!mult) {
				config.data = qs.stringify(config.data)
			}
		} else {
			if (config.data === undefined || config.data === null) {
				// 不传参的情况下 json类型的提交数据，校准为 空对象
				config.data = {}
			}
		}

		const validUrl = config.url ? config.url.toLowerCase() : ""
		const isAdd = cancelTokenWhiteList.every(item => !validUrl.includes(item))
		if (isAdd) {
			config.cancelToken = new axios.CancelToken(function (cancel) {
				store.commit("Add_CANCEL_TOKEN", { cancel, url: config.url })
			})
		}
		const { customConfig } = config
		if (customConfig?.removeToken) {
			delete config.headers["Admin-Token"]
		}
		return config
	},
	error => {
		// Do something with request error
		return Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async response => {
		const { url, baseURL } = response.config
		store.commit("Remove_CANCEL_TOKEN", { url: url.slice(baseURL.length) })

		const requestProp = response.config.requestProp || {} // 请求配置
		/**
		 * code为非20000是抛错 可结合自己业务进行修改
		 */
		const res = response.data
		getKey(res)
		if (response.status === 200 && response.config.responseType === "blob") {
			// 文件类型特殊处理
			const contentType =
				response.headers["Content-Type"] || response.headers["content-type"]
			if (
				contentType?.includes("json") ||
				(response.data && response.data?.type.includes("json"))
			) {
				const resultBlob = new Blob([response.data], {
					type: "application/json"
				})
				const data = await resultBlob.text()
				if (data) {
					const result = JSON.parse(data)
					// 附件下载反馈的302 忽略
					if (result.msg && result.code !== 302 && result.code !== 0) {
						errorMessage(result.msg, result.code == 1 ? "success" : "error")
					}

					// 结果为 0 返回到程序内
					if (result.code === 0) {
						Message({
							message: i18n.t("utils.c67c988c59e7a6259c969db8057609d0"),
							duration: 3000,
							type: "success"
						})
						return result
					}
				}
			} else if (isBlob(response.data)) {
				return response
			}
		} else if (res.code !== 0) {
			// 302	登录已失效
			if (res.code === 302) {
				if (res.data && res.data.extra === 1) {
					confirmMessage(
						i18n.t("utils.63cab64082962047dd3168bfd239cb0a", {
							1: res.data.extraTime
						})
					)
				} else {
					clearCacheEnterLogin()
				}
			} else if (res.code === 1005) {
				removeAuth()
					.then(() => {
						window.accessLogin = true
						setTimeout(() => {
							router.push(
								`/login?type=perfect&mobile=${
									res.data
								}&time=${new Date().getTime()}`
							)
						}, 500)
					})
					.catch(() => {})
			} else if (res.code === 1007) {
				// 该企业没有该用户
				// 忽略Cookies 读取
				window.sessionStorage.wkIgnoreCookies = true
				errorMessage(res.msg)
				router.push("/login")
			} else if (res.code === 1201) {
				removeAuth()
					.then(() => {
						setTimeout(() => {
							router.push({ name: "wechatLoginRegister" })
						}, 500)
					})
					.catch(() => {})
			} else {
				if (res.msg && !requestProp.disabledMessage) {
					// 添加多语言key
					// const langKey = setLangKey(res, null, 'error')
					// res.msg = getLangLabel(langKey, res.msg)
					errorMessage(res.msg)
				}
			}
			return Promise.reject(res)
		} else {
			return res
		}
	},
	error => {
		if (!axios.isCancel(error)) {
			// 取消请求的情况下，终端Promise调用链
			if (error.response) {
				const response = error.response
				if (response.status == 500) {
					errorMessage(i18n.t("utils.4293bc739c858ffc8e30b04bd2ef308d"))
				} else if (response.data && response.data.msg) {
					errorMessage(response.data.msg)
				}
			}
			return Promise.reject(error)
		}
	}
)

export default service
